package com.aerozhonghuan.oknet2;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

/**
 * 回调方法
 *
 * @param <T> 类型
 */
public abstract class CommonCallback<T extends Object> implements CommonCallbackInterface<T> {
    private static final String TAG = "CommonCallback";
    private Class cls;
    private Type responseType;

    public CommonCallback() {
    }

    /**
     * 指定 class
     *
     * @param cls class
     */
    public CommonCallback(Class<T> cls) {
        if (cls == null) throw new NullPointerException();
        this.cls = cls;
    }

    /**
     * 指定
     *
     * @param typeToken 类型
     */
    public CommonCallback(TypeToken<T> typeToken) {
        if (typeToken == null) throw new NullPointerException();
        this.responseType = typeToken.getType();
    }

    /**
     * 成功时
     *
     * @param messsageBodyObject 消息对象bean
     * @param commonMessage      message
     * @param allResponseString  所有的字符串消息体
     */
    public abstract void onSuccess(T messsageBodyObject, CommonMessage commonMessage, String allResponseString);

    /**
     * 失败时
     *
     * @param httpCode          http code
     * @param exception         ex
     * @param responseMessage   消息
     * @param allResponseString 所有的字符串消息体
     * @return isok
     */
    @Override
    public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) {
        return false;
    }

    /**
     * on start
     */
    @Override
    public void onStart() {

    }

    /**
     * 解析
     *
     * @param bodyString        bodyString
     * @param commonMessage     消息
     * @param allResponseString 所有的字符串消息体
     * @return bean
     */
    @Override
    @SuppressWarnings("unchecked")
    public T parseResponse(String bodyString, CommonMessage commonMessage, String allResponseString) {
        if (cls != null && cls.equals(String.class)) {
            return cast(bodyString);
        } else {
            if (cls != null) {
                return cast(new Gson().fromJson(bodyString, cls));
            } else if (responseType != null) {
                if (responseType == String.class) {
                    return (T) bodyString;
                }
                return cast(new Gson().fromJson(bodyString, responseType));
            } else
                return (T) bodyString;
        }
    }

    /**
     * 转换
     *
     * @param obj 对象
     * @param <T> 类型
     * @return 转换后的对象
     */
    @SuppressWarnings("unchecked")
    protected static <T> T cast(Object obj) {
        return (T) obj;
    }

    /**
     * 设置响应类型
     *
     * @param typeToken
     */
    public void setResponseType(TypeToken<T> typeToken) {
        if (typeToken == null) throw new NullPointerException();
        this.responseType = typeToken.getType();
    }
}
